//
//  WCBPostMessageViewController.m
//  WeChatBuniess
//
//  Created by Guo Rui on 2017/12/14.
//  Copyright © 2017年 GR Harry. All rights reserved.
//

#import "WCBPostMessageViewController.h"
#import "WCBPlaceholderTextView.h"
#import "WCBPlaceholderTextField.h"
#import "WCASessionManager.h"
#import "TFToast.h"
#import "WCBDataHelper.h"
#import "WCBComposingCompleteViewController.h"

@interface WCBPostMessageViewController ()
@property (strong, nonatomic) UIView *backgroundView;
@property (strong, nonatomic) UILabel *inputTitleLabel;
@property (strong, nonatomic) WCBPlaceholderTextView *messageTV;
@property (strong, nonatomic) WCBPlaceholderTextField *postNameTF;
@property (strong, nonatomic) UIButton *nextButton;

@property (copy, nonatomic) NSString *userName;
@property (copy, nonatomic) NSString *userId;
@end

@implementation WCBPostMessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.userId = [WCBDataHelper.sharedHelper getCurrentUserModel].userId;
    self.userName = [WCBDataHelper.sharedHelper getCurrentUserModel].nickName;
    
    self.view.backgroundColor = [UIColor colorWithRed:0.94 green:0.94 blue:0.95 alpha:1.00];
    self.title = @"填写寄语";
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    [self layoutViewLayout];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

#pragma mark - Private
- (void)layoutViewLayout
{
    CGFloat x, y, w, h;
    CGFloat width = CGRectGetWidth(self.view.frame);
    CGFloat height = CGRectGetHeight(self.view.frame);
    
    {
        x = 15;
        y = 15;
        w = width - 2 * x;
        h = 45;
        self.inputTitleLabel.frame = CGRectMake(x, y, w, h);
    }
    
    {
        x = 15;
        y = CGRectGetMaxY(self.inputTitleLabel.frame) + 20.f;
        w = width - 2 * x;
        h = 300;
        self.messageTV.frame = CGRectMake(x, y, w, h);
    }
    
    {
        x = 15;
        y = CGRectGetMaxY(self.messageTV.frame) + 20.f;
        w = width - 2 * x;
        h = 60;
        self.postNameTF.frame = CGRectMake(x, y, w, h);
    }
    
    {
        x = 0;
        y = 0;
        w = width;
        h = CGRectGetMaxY(self.postNameTF.frame) + 40.f;
        self.backgroundView.frame = CGRectMake(x, y, w, h);
    }
    
    {
        x = 30;
        y = CGRectGetMaxY(self.backgroundView.frame) + 50.f;
        w = width - 2 * x;
        h = 60.f;
        self.nextButton.frame = CGRectMake(x, y, w, h);
    }
}

#pragma mark - Actions
- (void)nextDidClick
{
    // 可以不填写
    if ((self.messageTV.text == nil || self.messageTV.text.length == 0) && (self.postNameTF.text == nil || self.postNameTF.text.length == 0)) {
        WCBComposingCompleteViewController *vc = [[WCBComposingCompleteViewController alloc] init];
        vc.bookModel = self.bookModel;
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
    
    // 如果填写了寄语，就必须填写署名
    if (self.messageTV.text != nil && self.messageTV.text.length > 0) {
        NSMutableDictionary *p = @{ @"bookId": self.bookModel.bookId, @"wishes" : self.messageTV.text }.mutableCopy;
        if (self.postNameTF.text != nil && self.postNameTF.text.length > 0) {
            [p setObject:self.postNameTF.text forKey:@"signature"];
        }
        
        __weak WCBPostMessageViewController *_self = self;
        [WCASessionManager POST:@"weimport/mtime/addWishes" parameters:p success:^(NSURLSessionDataTask *task, id responseObject) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if ([[responseObject objectForKey:@"code"] isEqualToString:@"000"]) {
                    [TFToast toast:@"添加寄语成功"];
                    
                    WCBComposingCompleteViewController *vc = [[WCBComposingCompleteViewController alloc] init];
                    vc.bookModel = _self.bookModel;
                    [_self.navigationController pushViewController:vc animated:YES];
                }
                else {
                    [_self alterWithTitle:@"发送失败" message:@"寄语发送失败，您可以选择重试或跳过" buttonTitles:@[@"重试", @"跳过"] clickBlock:^(int index) {
                        if (index == 0) {
                            [_self nextDidClick];
                        }
                        else {
                            WCBComposingCompleteViewController *vc = [[WCBComposingCompleteViewController alloc] init];
                            vc.bookModel = _self.bookModel;
                            [_self.navigationController pushViewController:vc animated:YES];
                        }
                    }];
                }
            });
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [TFToast toast:@"您的网络不给力，请检查网络后重试！"];
            });
        }];
    }
    else if (self.postNameTF.text != nil && self.postNameTF.text.length > 0) {
        [TFToast toast:@"填写署名必须要填写寄语哦~"];
    }
}

- (void)alterWithTitle:(NSString *)title message:(NSString *)message buttonTitles:(NSArray *)titles clickBlock:(void (^)(int index))block
{
    UIAlertController *alt = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alt animated:YES completion:nil];
    
    for (int i = 0; i < titles.count; i++) {
        NSString *bt = titles[i];
        UIAlertAction *action = [UIAlertAction actionWithTitle:bt style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if (block) block(i);
        }];
        [alt addAction:action];
    }
}

#pragma mark - Getter
- (UIView *)backgroundView
{
    if (!_backgroundView) {
        _backgroundView = [[UIView alloc] init];
        _backgroundView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_backgroundView];
    }
    return _backgroundView;
}

- (UILabel *)inputTitleLabel
{
    if (!_inputTitleLabel) {
        _inputTitleLabel = [[UILabel alloc] init];
        _inputTitleLabel.textColor = [UIColor blackColor];
        _inputTitleLabel.font = [UIFont systemFontOfSize:24];
        _inputTitleLabel.text = [NSString stringWithFormat:@"您现在可以给《%@》的扉页写下给TA的寄语啦~", self.bookModel.title];
        [self.backgroundView addSubview:_inputTitleLabel];
    }
    return _inputTitleLabel;
}

- (WCBPlaceholderTextView *)messageTV
{
    if (!_messageTV) {
        _messageTV = [[WCBPlaceholderTextView alloc] init];
        _messageTV.placeholder = @"请填写您的寄语(非必填)";
        _messageTV.maxInput = 140;
        [self.backgroundView addSubview:_messageTV];
    }
    return _messageTV;
}

- (WCBPlaceholderTextField *)postNameTF
{
    if (!_postNameTF) {
        _postNameTF = [[WCBPlaceholderTextField alloc] init];
        _postNameTF.placeholder = @"请填写寄语人署名(非必填)";
        _postNameTF.maxInput = 10;
        [self.backgroundView addSubview:_postNameTF];
    }
    return _postNameTF;
}

- (UIButton *)nextButton
{
    if (!_nextButton) {
        _nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_nextButton setTitle:@"下一步" forState:UIControlStateNormal];
        [_nextButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _nextButton.backgroundColor = [UIColor colorWithRed:0.11 green:0.62 blue:0.94 alpha:1.00];
        _nextButton.layer.cornerRadius = 5;
        _nextButton.layer.masksToBounds = YES;
        _nextButton.titleLabel.font = [UIFont systemFontOfSize:24];
        [_nextButton addTarget:self action:@selector(nextDidClick) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_nextButton];
    }
    return _nextButton;
}

@end
